﻿using CommonlyUtils;
using ImClientApi.Utils;
using ImModels.Service.Models.Data;
using ImModels.View;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using System.Security.Cryptography;

namespace ImClientApi.Controllers
{
    /// <summary>
    /// 企业管理相关控制器
    /// </summary>
    public class EnterpriseController : BaseAuthController
    {
        /// <summary>
        /// 企业注册开通IM 返回企业唯一标识 简单鉴权对请求参数序列化后的 AES 加密
        /// </summary>
        /// <param name="reqview"></param>
        /// <returns></returns>
        [HttpPost]
        [AnyUser]
        public async Task<ResView<EnterpriseRegRes>> OpenIm([FromBody] ReqView<EnterpriseRegReq> reqview)
        {
            try
            {
                if (reqview == null || reqview.Data == null)
                {
                    return new ResView<EnterpriseRegRes>() { code = 500, msg = "参数异常，不能为空" };
                }
                var data = reqview.Data;

                this.Request.Headers.TryGetValue("Authorization", out StringValues headAuth);
                var key = AESHelper.Encrypt(data.BizOrgId, ConfigUtils.AesKey, ConfigUtils.AesIv);
                if (key != headAuth)
                {
                    return await ReturnFailed(302, "参数鉴权错误");
                }

                var dbItem = await DbUtils.DbHelper.GetOneAsync<Enterprise>(p => p.BizOrgId == data.BizOrgId);

                var kid = Builder.GetNewSnowId();
                var secret = Md5Helper.Encrypt(kid.ToString());
                if (dbItem == null || dbItem.KID == 0)
                {
                    #region 新注册一个企业IM
                    var addDb = await DbUtils.DbHelper.AddItemAsync<Enterprise>(new Enterprise()
                    {
                        KID = kid,
                        FullName = data.FullName,
                        NickName = data.NickName,
                        BizOrgId = data.BizOrgId,
                        ContactTel = data.ContactTel,
                        ExJson = data.ExJson.ToJson(),
                        HeadImg = data.HeadImg,
                        CreateUserId = data.CreateUserId,
                        Secret = secret
                    });
                    if (addDb == 0)
                    {
                        return new ResView<EnterpriseRegRes>() { code = 500, msg = "企业开通IM失败，请稍候重试" };
                    }
                    #region 生成一个UserId为0的系统用户
                    await DbUtils.DbHelper.AddItemAsync<Users>(new Users()
                    {
                        KID = Builder.GetNewSnowId(),
                        BizUserId = kid.ToString(),
                        FullName = "系统消息",
                        HeadImg = data.HeadImg,
                        EnterpriseId = kid,
                        IsAdmin = 1,
                        JobName = "系统",
                        NickName = "系统消息"
                    });
                    //await DbUtils.DbHelper.AddItemAsync<ImGroups>(new ImGroups()
                    //{
                    //    KID = Builder.GetNewSnowId(),
                    //    Comment = "系统全员群",
                    //    FullName = "系统消息",
                    //    HeadImg = data.HeadImg,
                    //    EnterpriseId = kid,
                    //    CreateTime = DateTime.Now
                    //});
                    #endregion

                    #endregion
                }
                else
                {
                    kid = dbItem.KID;
                    secret = Md5Helper.Encrypt(kid.ToString());
                }
                return new ResView<EnterpriseRegRes>()
                {
                    code = 200,
                    msg = "开通成功",
                    data = new EnterpriseRegRes()
                    {
                        EnterpriseId = kid.ToString(),
                        Secret = secret
                    }
                };
            }
            catch (Exception ex)
            {
                return new ResView<EnterpriseRegRes>() { code = 500, msg = "访问异常:" + ex.Message };
            }
        }

        /// <summary>
        /// 企业注销账号 后续不能再登录
        /// </summary>
        /// <param name="reqview"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResView> LogOffIm([FromBody] ReqView reqview)
        {
            if (reqview.AppId == 0)
            {
                return new ResView() { code = 500, msg = "参数异常，AppId[企业ID]不能为空" };
            }
            else
            {
                var delDb = await DbUtils.DbHelper.DeleteItemAsync<Enterprise>(p => p.KID == reqview.AppId);
                return new ResView()
                {
                    code = (delDb > 0 ? 200 : 500),
                    msg = (delDb > 0 ? "注销成功" : "注销失败")
                };
            }
        }

        /// <summary>
        /// 企业刷新秘钥
        /// </summary>
        /// <param name="reqview"></param>
        /// <returns></returns>
        [HttpPost]
        public ResView RefreshSecret([FromBody] ReqView reqview)
        {
            return new ResView() { code = 0, msg = "刷新成功" };
        }
    }
}
